﻿/// <reference path="JsonProxy.aspx" />
/// <reference path="Scripts/jquery-2.0.0.js" />
/// <reference path="Scripts/jquery-2.0.0.intellisense.js" />
/// <reference path="Scripts/Leaflet.js" />
/// <reference path="Scripts/Leaflet.BoundaryCanvas.js" />

var cmk = 'f8a57472669e4fcda99ebd5ed0f72918';
var area = [];  //enpty array
var start = new L.LatLng(48.008, 16.235);
var end = new L.LatLng(48.00352, 16.25779);
var map = null;

//Map Styling
var tileLayer = '', backTileLayer = '';
var subdomains = 'abc';
//styleId = 997; tileLayer = 'http://{s}.tile.cloudmade.com/' + cmk + '/' + styleId + '/256/{z}/{x}/{y}.png'; //CloudMade
styleId = 93587; tileLayer = 'http://{s}.tile.cloudmade.com/' + cmk + '/' + styleId + '/256/{z}/{x}/{y}.png'; //CloudMade ohne Restaurants, etc
backStyleId = 48535; backTileLayer = 'http://{s}.tile.cloudmade.com/' + cmk + '/' + backStyleId + '/256/{z}/{x}/{y}.png'; //CloudMade gray
//tileLayer = 'http://otile{s}.mqcdn.com/tiles/1.0.0/osm/{z}/{x}/{y}.png'; subdomains = '1234'; //MapQuest
//tileLayer = 'http://otile{s}.mqcdn.com/tiles/1.0.0/sat/{z}/{x}/{y}.png'; subdomains = '1234'; //MapQuest.Sat (no tiles for detailed zoom)
//tileLayer = 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png'; //OpenStreetMap
//tileLayer = 'http://{s}.tile.osm.org/{z}/{x}/{y}.png'; //OpenStreetMap (same as line before)
//tileLayer = 'http://{s}.tile.opencyclemap.org/cycle/{z}/{x}/{y}.png' //OpenCycleMap
//tileLayer = 'http://{s}.tiles.mapbox.com/v3/' + 'examples.map-zr0njcqy' + '/{z}/{x}/{y}.png' //MapBox


function DrawBoundaries(OsmRelationId) {

  $.getJSON('JsonProxy.aspx?u=' + 'http://ra.osmsurround.org/showRelation?relationId=' + OsmRelationId,
    function (data) { //success

      var points = [];
      switch (data.features[0].geometry.type) {
        case "MultiLineString":
          var ways = data.features[0].geometry.coordinates; //data.features.geometry: array von lines ('wege')
          if (ways && ways.length) {
            //wege aneinanderhängen
            while (ways.length) {
              for (var w = 0; w < ways.length; w++) {
                var way = ways[w];
                try {
                  if (points.length === 0 || (points.length > 0 && points[points.length - 1][0] === way[0][0] && points[points.length - 1][1] === way[0][1])) { //wenn points leer oder erter Punkt des Weges === letzer Punkt von points ... weg übertragen
                    for (var p = 0; p < way.length; p++) {
                      points.push(way[p]);
                    }
                    //console.log('fLoading [' + w + ']: ' + JSON.stringify(way[0]) + ' - ' + JSON.stringify(way[way.length - 1]));
                    //L.polyline(L.GeoJSON.coordsToLatLngs(way)).addTo(map);
                    ways.splice(w, 1); //Weg löschen
                  } //if
                  else if (points.length > 0 && points[points.length - 1][0] === way[way.length - 1][0] && points[points.length - 1][1] === way[way.length - 1][1]) { //wenn letzter Punkt des Weges === letzer Punkt von points ... weg ungekehrt übertragen
                    for (var q = way.length - 1; q > -1; q--) {
                      points.push(way[q]);
                    }
                    //console.log('rLoading [' + w + ']: ' + JSON.stringify(way[way.length - 1]) + ' - ' + JSON.stringify(way[0]));
                    //L.polyline(L.GeoJSON.coordsToLatLngs(way)).addTo(map);
                    ways.splice(w, 1); //Weg löschen
                  } //else if
                } catch (e) {
                  console.error(e.message); //im IE, Opera, Crome, FF(Firefox) mit F12 anzeigen (in Firefox zuerst 'Firebug' installieren)
                } //catch
              }
              var iter = 0; if (++iter > 1000) break; //Abbruchbedingung, wenn nicht zusammenhängende objekte im Array
            } //while
          } //if (ways && ways.length)
          break;
        case "Polygon":
          points = data.features[0].geometry.coordinates;
          break;
        default:
          console.error("Ungültiger Feature Typ '" + data.features[0].geometry.type);
          break;
      } //switch (geometry.type)

      console.log(JSON.stringify(points));

      //Array von Koordinaten in Array von LatLng konvertieren
      var boundary = L.GeoJSON.coordsToLatLngs(points); //Leaflet funktion

      //Farbige Karte in errechneten Boundaries über graue Karte legen
      var tiles = L.TileLayer.boundaryCanvas(tileLayer, {
        subdomains: subdomains,
        attribution: ' <a href="http://openstreetmap.org">OpenStreetMap</a> — <a href="http://onyourway.at">onYOURway</a>',
        maxZoom: 18,
        boundary: boundary
      });
      tiles.addTo(map);

      //Polygon zeichnen
      L.polygon(boundary, { color: "#ff7800", weight: 2 })
        .addTo(map);

      //passend einzoomen
      if (data.bbox) {
        var southWest = new L.LatLng(data.bbox[1], data.bbox[0]);
        var northEast = new L.LatLng(data.bbox[3], data.bbox[2]);
        map.fitBounds(new L.LatLngBounds(southWest, northEast));
      }

    },
    function (event, xhr, options, exc) { //error
      alert(event.statusText);
    }
  );

}

function GetLocations() {
  //get TestLocations
  var loc = [
    { marker: [48.0062713, 16.2204271], popup: "Club2-Bar" },
    { marker: [48.0064036, 16.2332904], popup: "Kebab&Pizza House" },
    { marker: [48.0073252, 16.2344778], popup: "Cafe Central" },
    { marker: [48.0081866, 16.2339371], popup: "Eispeter" },
    { marker: [48.0071013, 16.2314995], popup: "Backhaus Annamühle" },
    { marker: [48.0073875, 16.2317153], popup: "Kur-Konditorei Trahbüchler" },
    { marker: [48.0078342, 16.2326816], popup: "Cafe-Restaurant Unicum" },
    { marker: [48.0092436, 16.2356628], popup: "Cafe-Restaurant Batzenhäusel" },
    { marker: [48.0109428, 16.2337826], popup: "Cafe Florian" },
    { marker: [48.0057805, 16.2284439], popup: "Restaurant Rauhenstein" },
    { marker: [48.0054704, 16.2315081], popup: "Restaurant Primavera" },
    { marker: [48.0034777, 16.2360657], popup: "Filou" },
    { marker: [48.0064581, 16.2331389], popup: "Glamor" },
    { marker: [48.0055967, 16.2321003], popup: "Goldener Löwe" },
    { marker: [48.0072678, 16.2316368], popup: "Badener Eck" },
    { marker: [48.0074290, 16.2318477], popup: "Kupferdachl" },
    { marker: [48.0066649, 16.2356365], popup: "Lehner" },
    { marker: [48.0066189, 16.2316368], popup: "Bürgerstube" },
    { marker: [48.0085196, 16.2339714], popup: "El Greco" },
    { marker: [48.0097025, 16.2339199], popup: "Café Metternich" },
    { marker: [48.0075549, 16.2330959], popup: "Café Damals" },
    { marker: [48.0090307, 16.2339628], popup: "Café Konditorei Vock" },
    { marker: [48.0091570, 16.2339628], popup: "Restaurant zum Theresienschlössel" },
    { marker: [48.0063147, 16.2329070], popup: "El Gaucho" },
    { marker: [48.0097140, 16.2332161], popup: "Herzoghof" },
    { marker: [48.0066189, 16.2328385], popup: "Almkuchl" },
    { marker: [48.0178304, 16.2295261], popup: "Rudolfshof" },
    { marker: [48.0037923, 16.2144899], popup: "Weinbau Schmid-Kofler (Buschenschank/Heuriger)" },
    { marker: [48.0080735, 16.2252073], popup: "Cafe Restaurant Doblhoff" },
    { marker: [47.9986076, 16.2553308], popup: "Halle B" },
    { marker: [48.0072995, 16.2344213], popup: "Palmira" },
    { marker: [48.0066714, 16.2328093], popup: "Friends" },
    { marker: [48.0052609, 16.2317230], popup: "Schnitzl Platz´l" },
    { marker: [48.0074000, 16.2892966], popup: "Maschler" },
    { marker: [48.0068087, 16.2341578], popup: "Muggi's Steira Eck" },
    { marker: [48.0041670, 16.2147602], popup: "Gasthof Martinek" },
    { marker: [48.0066656, 16.2171520], popup: "Cafe Esplanade" },
    { marker: [48.0068399, 16.2172727], popup: "Backhaus Annamühle (Filiale)" },
    { marker: [48.0071363, 16.2268116], popup: "WASABI" },
    { marker: [48.0049888, 16.2425642], popup: "Wok&Tea" },
    { marker: [48.0051928, 16.2703216], popup: "Sängerhof" },
    { marker: [48.0174291, 16.2657727], popup: "Rathausstub'n Pfaffstätten" },
    { marker: [48.0174493, 16.2599464], popup: "Weinbau Kernbichler ZWILLINGE" },
    { marker: [48.0173078, 16.2661384], popup: "Weinbau Jürgen Hösl" },
    { marker: [48.0180632, 16.2666187], popup: "Steinbrunnenheuriger Gabriele Hofer" },
    { marker: [48.0141142, 16.2651680], popup: "Weinbau Familie Fuchs" },
    { marker: [48.0174725, 16.2595257], popup: "Weinbau Österreicher-Polt" },
    { marker: [48.0138271, 16.2647012], popup: "Mühlfeldhof - Weingut Leopold Kernbichler" },
    { marker: [48.0150900, 16.2644823], popup: "Weingut Familie Robert Strasser" },
    { marker: [48.0167712, 16.2612302], popup: "Weingut Laffer" },
    { marker: [48.0171117, 16.2660831], popup: "Zakini" },
    { marker: [48.0152670, 16.2640848], popup: "Weinbau Silvia Jeitschko" },
    { marker: [48.0152836, 16.2635932], popup: "Gassl Cafe" },
    { marker: [48.0171894, 16.2604411], popup: "Josef und Christine Kernbichler" },
    { marker: [48.0163766, 16.2615797], popup: "Cafe Domino" },
    { marker: [48.0010610, 16.2159557], popup: "Cafe-Bar Wenzelspitz" },
    { marker: [48.0106100, 16.2329541], popup: "Cafe Bistro" },
    { marker: [48.0105829, 16.2324584], popup: "Do&Co Casino Restaurant" },
    { marker: [48.0076877, 16.2326634], popup: "Al Capone" },
    { marker: [48.0079028, 16.2341822], popup: "Amterl" },
    { marker: [48.0088100, 16.2346177], popup: "Il Castello" },
    { marker: [48.0088522, 16.2347247], popup: "Segafredo Espresso" },
    { marker: [48.0072729, 16.2268641], popup: "Cafe Konditorei Ullmann" },
    { marker: [48.0063722, 16.2365443], popup: "SAM" },
    { marker: [48.0148068, 16.2599446], popup: "Böck" },
    { marker: [48.0094702, 16.2654520], popup: "Rad_ Heuriger" },
    { marker: [48.0180452, 16.2565156], popup: "Familie Schwarz" },
    { marker: [48.0013945, 16.2476547], popup: "Schnitzel Imbiss" },
    { marker: [48.0065098, 16.2311389], popup: "Willi" }
  ];

  return loc;
}

function Umriss(Poly, Radius) {  // Noch die 2.Hälfte zu implementieren doch diese geht analog, daher zuerst analyse mit der einzelnen, ...
  var Genauigkeit = 15;                           //Genauigkeit der Berechnung
  var R_Vec = [[0, 0], [0, 0], [0, 0]];           //Ablage der Richtungsvektoren
  var Umriss = [];                                //Initialisierung des Umschliesenden Poly
  var Phi = Math.PI / (2 ^ (Genauigkeit - 1));    //Drehwinkel in abhängigkeit der Genauigkeit

  /* UNTERFUNKTIONEN */
  /* Vektor Normieren auf die Länge leng*/
  function Norm_Vec(Vec, leng) {
    var VecNorm = [0, 0];
    var Norm = (leng / Math.sqrt(Vec[0] * Vec[0] + Vec[1] * Vec[1]));
    VecNorm[0] = Vec[0] * Norm;
    VecNorm[1] = Vec[1] * Norm;
    return VecNorm;
  }

  /* Drehung des Vektors um Beta */
  function Rotate(Vec, Beta) {
    var VecRot = [0, 0];
    VecRot[0] = (Math.cos(Beta) * Vec[0]) - (Math.sin(Beta) * Vec[1]);
    VecRot[1] = (Math.sin(Beta) * Vec[0]) + (Math.cos(Beta) * Vec[1]);
    return VecRot;
  }

  /* Boolsche überprüfung auf orthogonalität */
  function isOrtho(Vec1, Vec2) {
    var Winkel = Math.acos((Vec1[0] * Vec2[0]) + (Vec1[1] * Vec2[1]));
    var Phalb = Math.PI / 2;
    var Wink = -1;
    if (Winkel < Phalb) {
      Wink = 0;
    }
    else {
      Wink = 1;
    }
    return Wink;
  }

  /* BERECHNEN DER STARTWERTE */
  R_Vec[2][0] = Poly[2][0] - Poly[1][0];     //Berechnung und normierung des 1.Richtungsvektors
  R_Vec[2][1] = Poly[2][1] - Poly[1][1];     //  auf dem 3. ablageplatz der Richtungsvektoren
  R_Vec[2] = Norm_Vec(R_Vec[2], 1);

  R_Vec[0][0] = -R_Vec[2][1];                //Kippen des Rixhungsvektors und in der 1. 
  R_Vec[0][1] = R_Vec[2][0];                 //  Ablage gespeichert

  Umriss.push([(Poly[0][0] + Norm_Vec(R_Vec[0], Radius)[0]), (Poly[0][1] + Norm_Vec(R_Vec[0], Radius)[1])]);
  //Zuweisung des 1. Punktes

  /* 1.HALB-KREIS */
  var Abbruch = 1;
  while (Abbruch) {
    R_Vec[0] = Rotate(R_Vec[0], Phi);
    if (isOrtho(R_Vec[0], R_Vec[2])) {
      Umriss.push([(Poly[0][0] + Norm_Vec(R_Vec[0], Radius)[0]), (Poly[0][1] + Norm_Vec(R_Vec[0], Radius)[1])]);
    }
    else {
      R_Vec[0][0] = R_Vec[2][1];
      R_Vec[0][1] = -R_Vec[2][0];
      Umriss.push([(Poly[0][0] + Norm_Vec(R_Vec[0], Radius)[0]), (Poly[0][1] + Norm_Vec(R_Vec[0], Radius)[1])]);
      Abbruch = 0;
    }
  }

  /* BERECHNUNG DES SCHLIESENDEN PLOY. AUF EINER SEITE */
  for (i = 1; i < (Poly.length - 1) ; i++) {

    R_Vec[1] = R_Vec[2];

    //var Abbruch = 1;
    //var count = 0;
    //while (Abbruch) {


    //    if(i+count +1 < (Poly.length - 1)) {
    R_Vec[2][0] = Poly[i + /*count +*/ 1][0] - Poly[i][0];
    R_Vec[2][1] = Poly[i + /*count +*/ 1][1] - Poly[i][1];
    //    }
    //    else {
    //        break;
    //    }


    //    var Norm = Math.sqrt((R_Vec[2][0] ^ 2) + (R_Vec[2][1] ^ 2));
    //    if (Norm < (Radius/50)) {
    //        Abbruch = 0;
    //    }
    //    else {
    //        if (count >= 20) {
    //            Abbruch = 0;
    //        }
    //    }
    //    count = count + 1;
    //}


    if (isOrtho(R_Vec[0], R_Vec[2])) {
      var Abbruch = 1;
      while (Abbruch) {
        R_Vec[0] = Rotate(R_Vec[0], Phi);
        if (isOrtho(R_Vec[0], R_Vec[2])) {
          Umriss.push([(Poly[i][0] + Norm_Vec(R_Vec[0], Radius)[0]), (Poly[i][1] + Norm_Vec(R_Vec[0], Radius)[1])]);
        }
        else {
          R_Vec[0][0] = R_Vec[2][1];
          R_Vec[0][1] = -R_Vec[2][0];
          Umriss.push([(Poly[i][0] + Norm_Vec(R_Vec[0], Radius)[0]), (Poly[i][1] + Norm_Vec(R_Vec[0], Radius)[1])]);
          Abbruch = 0;
        }
      }
    }
    else {
      var Theta = Math.acos((-R_Vec[1][0] * R_Vec[2][0]) + (-R_Vec[1][1] * R_Vec[2][1]));
      R_Vec[0] = Rotate([-R_Vec[1][0], -R_Vec[1][1]], Theta);
      Umriss.push([(Poly[i][0] + Norm_Vec(R_Vec[0], Radius / Math.abs(Math.sin(Theta / 2)))[0]), (Poly[i][1] + Norm_Vec(R_Vec[0], Radius / Math.abs(Math.sin(Theta / 2)))[1])]);
      R_Vec[0][0] = R_Vec[2][1];
      R_Vec[0][1] = -R_Vec[2][0];
    }


    //i = i + count;


  }

  /* UMKEHREN DES RICHTUNGSVEKTORS UND SELBIGER VORGANZ ZURÜCK */
  R_Vec[2][0] = -R_Vec[2][0];
  R_Vec[2][1] = -R_Vec[2][1];

  /* 2.HALBKREIS */
  Umriss.push([(Poly[Poly.length - 1][0] + Norm_Vec(R_Vec[0], Radius)[0]), (Poly[Poly.length - 1][1] + Norm_Vec(R_Vec[0], Radius)[1])]);

  var Abbruch = 1;
  while (Abbruch) {
    R_Vec[0] = Rotate(R_Vec[0], Phi);
    if (isOrtho(R_Vec[0], R_Vec[2])) {
      Umriss.push([(Poly[Poly.length - 1][0] + Norm_Vec(R_Vec[0], Radius)[0]), (Poly[Poly.length - 1][1] + Norm_Vec(R_Vec[0], Radius)[1])]);
    }
    else {
      R_Vec[0][0] = R_Vec[2][1];
      R_Vec[0][1] = -R_Vec[2][0];
      Umriss.push([(Poly[Poly.length - 1][0] + Norm_Vec(R_Vec[0], Radius)[0]), (Poly[Poly.length - 1][1] + Norm_Vec(R_Vec[0], Radius)[1])]);
      Abbruch = 0;
    }
  }

  /* BERECHNUNG DES SCHLIESENDEN PLOY. AUF DER ANDEREN SEITE */
  for (i = (Poly.length - 1) ; i > 0 ; i--) {
    R_Vec[1] = R_Vec[2];
    R_Vec[2][0] = Poly[i - 1][0] - Poly[i][0];
    R_Vec[2][1] = Poly[i - 1][1] - Poly[i][1];
    if (isOrtho(R_Vec[0], R_Vec[2])) {
      var Abbruch = 1;
      while (Abbruch) {
        R_Vec[0] = Rotate(R_Vec[0], Phi);
        if (isOrtho(R_Vec[0], R_Vec[2])) {
          Umriss.push([(Poly[i][0] + Norm_Vec(R_Vec[0], Radius)[0]), (Poly[i][1] + Norm_Vec(R_Vec[0], Radius)[1])]);
        }
        else {
          R_Vec[0][0] = R_Vec[2][1];
          R_Vec[0][1] = -R_Vec[2][0];
          Umriss.push([(Poly[i][0] + Norm_Vec(R_Vec[0], Radius)[0]), (Poly[i][1] + Norm_Vec(R_Vec[0], Radius)[1])]);
          Abbruch = 0;
        }
      }
    }
    else {
      var Theta = Math.acos((-R_Vec[1][0] * R_Vec[2][0]) + (-R_Vec[1][1] * R_Vec[2][1]));
      R_Vec[0] = Rotate([-R_Vec[1][0], -R_Vec[1][1]], Theta);
      Umriss.push([(Poly[i][0] + Norm_Vec(R_Vec[0], Radius / Math.abs(Math.sin(Theta / 2)))[0]), (Poly[i][1] + Norm_Vec(R_Vec[0], Radius / Math.abs(Math.sin(Theta / 2)))[1])]);
      R_Vec[0][0] = R_Vec[2][1];
      R_Vec[0][1] = -R_Vec[2][0];
    }
  }

  /* SCHLIEßEN DES POLYGONZUGS */
  Umriss.push(Umriss[0]);

  return Umriss;
}

function Umriss2(Poly, Radius) {
  var Umriss = [];
  var Genauigkeit = 15;
  var Phi = Math.Pi / (2 ^ Genauigkeit);
  var AreaArray = [];

  /* UNTERFUNKTIONEN */
  /* Vektor Normieren auf die Länge "leng"*/
  function Norm_Vec(Vec, leng) {
    var VecNorm = [0, 0];
    var Norm = (leng / Math.sqrt(Vec[0] * Vec[0] + Vec[1] * Vec[1]));
    VecNorm[0] = Vec[0] * Norm;
    VecNorm[1] = Vec[1] * Norm;
    return VecNorm;
  }

  /* Drehung des Vektors um Beta */
  function Rotate(Vec, Beta) {
    var VecRot = [0, 0];
    VecRot[0] = (Math.cos(Beta) * Vec[0]) - (Math.sin(Beta) * Vec[1]);
    VecRot[1] = (Math.sin(Beta) * Vec[0]) + (Math.cos(Beta) * Vec[1]);
    return VecRot;
  }

  /* Bereichsbestimung um die Gerade-Verbindung der Punkte P1 zu P2 */
  function CalculateArea(P1, P2, RADIUS, GENAU) {
    var Area = [];
    var RVec = [0, 0];
    var Psy = Math.PI / (2 ^ GENAU);

    /* Berechnung des Normalenvektors auf die Verbindungsgerade von P1 zu P2 */
    RVec[0] = -(P2[1] - P1[1]);
    RVec[1] = P2[0] - P1[0];
    RVec = Norm_Vec(RVec, RADIUS);

    /* Berechnung des von den Punkten bestimmten Bereich */
    Area.push([(P1[0] + RVec[0]), (P1[1] + RVec[1])]);
    for (var i = 0; i < (2 ^ GENAU) ; i++) {
      RVec = Rotate(RVec, Psy);
      Area.push([(P1[0] + RVec[0]), (P1[1] + RVec[1])]);
    }
    Area.push([(P2[0] + RVec[0]), (P2[1] + RVec[1])]);
    for (var i = 0; i < (2 ^ GENAU) ; i++) {
      RVec = Rotate(RVec, Psy);
      Area.push([(P2[0] + RVec[0]), (P2[1] + RVec[1])]);
    }
    Area.push(Area[0]);

    return Area;
  }

  function FillAreaArray(POLY, RADIUS, GENAU) {
    var AreaArray = [];
    for (var i = 0; i < (POLY.length - 1) ; i++) {
      AreaArray.push(CalculateArea(POLY[i], POLY[i + 1], RADIUS, GENAU));
    }
    return AreaArray;
  }

  function isPinArea(P, AREA) {
    var RVeci = [0, 0];
    var Angles = [];

    function Numsort(a, b) {
      return a - b;
    }

    for (var i = 0; i < AREA.length; i++) {
      RVeci[0] = AREA[i][0] - P[0];
      RVeci[1] = AREA[i][1] - P[1];
      if (RVeci[0] > 0) {
        if (RVeci[1] >= 0) {
          Angles.push(Math.atan(RVeci[1] / RVeci[0]));
        }
        else {
          Angles.push(-Math.atan(-RVeci[1] / RVeci[0]));
        }
      }
      if (RVeci[0] = 0) {
        if (RVeci[1] >= 0) {
          Angles.push(Math.PI);
        }
        else {
          Angles.push(-Math.PI);
        }
      }
      else {
        if (RVeci[1] >= 0) {
          Angles.push(Math.atan(RVeci[1] / RVeci[0]) + (Math.PI / 2));
        }
        else {
          Angles.push(-Math.atan(RVeci[1] / RVeci[0]) + Math.PI);
        }
      }
    }

    Angles = Angles.sort(Numsort);

    var isElement = 0;
    if (Angles[Angles.length - 1] - Angles[0] > Math.PI) {
      isElement = 1;
    }

    return isElement;
  }

  function BreakeAreas(AREAARRAY) {
    for (var i = 0; i < AREAARRAY.length; i++) {
      for (var k = i + 1; k < AREAARRAY.length; k++) {

      }
    }
  }



  Umriss = FillAreaArray(Poly, Radius, Genauigkeit);

  return Umriss;
}

function Umriss3(Poly, Radius) {



}

function InitializeMap() {
  /* INITIALIZE MAP */

  var map = L.map('map', { center: new L.LatLng(48.008, 16.235), zoom: 14 });

  var tiles = L.tileLayer(backTileLayer, {
    subdomains: subdomains,
    attribution: ' <a href="http://openstreetmap.org">OpenStreetMap</a> — <a href="http://onyourway.at">onYOURway</a>',
    maxZoom: 18
  });
  tiles.addTo(map);


  ///* ADD BOUNDARIES */
  DrawBoundaries(111479); //Baden

  ////L.polygon(GetBoundaries())
  ////  .addTo(map);

  /* ADD STUFF */

  //var marker = L.marker([48.00352, 16.25779]).addTo(map);
  //marker.bindPopup('I am a <b>popup</b>.').openPopup();

  ///* DEFINE EVENTHANDLER */

  //function onMapClick(e) {
  //  //alert('Location: ' + e.latlng);  //MessageBox
  //  //document.getElementById('output').innerHTML = 'Location: <b>' + e.latlng + '</b>';
  //  $('#output').html('Location: <b>' + e.latlng + '</b>');
  //}

  ///* HOOK EVENTHANDLER */
  //map.on('click', onMapClick);

  /* DEFINE AND HOOK EVENDHANDLER */
  map.on('click', function (e) {
    //$('#output').html('Location: <b>' + e.latlng + '</b>');

    area.push(e.latlng);

  });

  /* TESTING POLYUMRISS */
  var POLY = [                  //Initialisierung eines beliebigen Polygonzugs
      [16.220034, 48.022057], [16.218332, 48.022057], [16.216234, 48.022152], [16.215944, 48.022076], [16.215101, 48.02204], [16.21428, 48.02197], [16.213741, 48.02193], [16.213259, 48.02195], [16.212833, 48.02197], [16.212494, 48.021683], [16.21221, 48.021305], [16.21187, 48.02096], [16.211672, 48.02085], [16.211388, 48.020794], [16.210766, 48.020737], [16.209972, 48.02078], [16.209717, 48.020817], [16.209406, 48.02087], [16.207335, 48.02127], [16.207165, 48.021156], [16.206995, 48.021008], [16.206003, 48.021255], [16.205523, 48.02137], [16.205153, 48.021465], [16.204672, 48.02158], [16.204247, 48.02175], [16.203423, 48.022186], [16.203396, 48.02234], [16.203367, 48.022568], [16.203028, 48.022587], [16.202856, 48.022587], [16.202347, 48.022453], [16.201553, 48.022038], [16.201412, 48.02198], [16.201355, 48.02196], [16.201185, 48.02189], [16.201015, 48.02189], [16.200903, 48.021908], [16.200674, 48.02198], [16.200562, 48.022076], [16.200504, 48.022133], [16.200222, 48.02238], [16.199766, 48.02295], [16.19954, 48.02312], [16.199116, 48.02331], [16.19869, 48.023445], [16.198208, 48.023502], [16.197302, 48.02358], [16.196707, 48.02354], [16.196253, 48.02343], [16.19577, 48.023277], [16.195118, 48.02307], [16.194893, 48.023052], [16.194609, 48.02307], [16.19441, 48.023148], [16.194183, 48.02326], [16.193787, 48.02364], [16.19356, 48.023926], [16.193304, 48.024193], [16.193077, 48.024437], [16.192568, 48.02423], [16.191973, 48.02383], [16.19166, 48.023663], [16.191462, 48.023567], [16.191122, 48.0233], [16.190613, 48.023018], [16.19013, 48.02268], [16.189903, 48.02241], [16.18982, 48.022316], [16.189724, 48.022224], [16.18965, 48.02194], [16.189537, 48.021652], [16.189566, 48.02116], [16.189592, 48.021103], [16.189678, 48.020893], [16.189848, 48.02072], [16.190115, 48.020657], [16.19026, 48.020634], [16.190569, 48.020584], [16.19073, 48.020428], [16.190893, 48.020176]
  ];
  var LatLng_POLY = [];         //Umwandeln in Lat,- and Length coordinates
  for (var i = 0; i < POLY.length; i++) {
    LatLng_POLY.push(new L.LatLng(POLY[i][1], POLY[i][0]));
  }

  var Test_Zug = L.polyline(LatLng_POLY)
      .addTo(map);              //Zeichnen des Test-Polygon-Zugs

  //var Test_Umriss = L.polyline(Umriss(POLY, 0.001)).addTo(map);
  //Zeichen des Umrisses

  /* END TESTING */

  return map;
}

//Route zwischen zwei Punkten berechnen
function DrawRoute(start, end) {

  var url = 'JsonProxy.aspx?u=' + 'http://routes.cloudmade.com/' + cmk + '/api/0.3/48.008,16.235,48.00352,16.25779/bicycle.js?lang=de&units=km';

  $.getJSON(url,
    function (route) { //success
      //route = { "version": 0.3, "status": 0, "route_summary": { "total_distance": 2133, "total_time": 513, "start_point": "Grabengasse", "end_point": "Lokalbahnzeile" }, "route_geometry": [[48.00816, 16.235531], [48.007969, 16.235661], [48.007141, 16.23617], [48.007359, 16.23703], [48.007511, 16.237801], [48.00708, 16.237961], [48.006611, 16.238689], [48.005459, 16.239941], [48.005589, 16.24048], [48.005669, 16.24119], [48.005699, 16.24177], [48.005669, 16.242371], [48.005589, 16.242979], [48.00552, 16.24374], [48.005379, 16.243879], [48.005169, 16.244289], [48.005058, 16.244459], [48.00494, 16.244459], [48.004082, 16.245729], [48.00388, 16.24604], [48.00367, 16.24633], [48.003399, 16.24671], [48.003189, 16.247101], [48.002979, 16.247351], [48.002289, 16.247589], [48.00227, 16.24802], [48.002399, 16.249491], [48.002541, 16.25045], [48.002579, 16.2507], [48.002529, 16.250731], [48.002491, 16.250811], [48.002491, 16.25091], [48.002529, 16.250971], [48.002468, 16.25111], [48.002411, 16.25135], [48.002331, 16.25185], [48.00227, 16.252399], [48.002251, 16.25284], [48.002319, 16.25308], [48.002548, 16.253771], [48.00267, 16.254419], [48.00272, 16.2563], [48.00275, 16.25639], [48.002769, 16.257259], [48.002869, 16.257259], [48.00293, 16.257271], [48.003559, 16.25761]], "route_instructions": [["Richtung Südost auf Grabengasse", 122, 0, 29, "0.1 km", "SE", 155.2], ["Bei Am Fischertor links abbiegen", 128, 2, 31, "0.1 km", "E", 69.7, "TL", 272.3], ["Bei Annagasse rechts abbiegen", 359, 4, 86, "0.4 km", "S", 165.6, "TR", 92.0], ["Bei Christalniggasse links abbiegen", 422, 7, 101, "0.4 km", "E", 71.0, "TL", 287.0], ["Weiter", 18, 15, 4, "18 m", "SE", 132.2, "C", 3.9], ["Bei B212\/Dammgasse rechts abbiegen", 13, 16, 2, "13 m", "S", 182.6, "TR", 50.4], ["Links halten bei Prinz-Solms-Straße", 199, 17, 48, "0.2 km", "SE", 135.2, "TSLL", 312.7], ["Weiter auf Prinz-Solms-Straße", 32, 19, 8, "32 m", "SE", 137.0, "C", 2.9], ["Weiter auf Prinz-Solms-Straße", 224, 20, 54, "0.2 km", "SE", 136.5, "C", 359.5], ["Bei Leesdorfer Hauptstraße links abbiegen", 344, 24, 83, "0.3 km", "E", 92.3, "TL", 285.6], ["Bei Leesdorfer Hauptstraße rechts abbiegen", 41, 28, 10, "41 m", "S", 160.3, "TR", 63.6], ["Im Kreisverkehr zweite Ausfahrt (Kanalgasse) nehmen", 616, 32, 148, "0.6 km", "SE", 122.2, "EXIT2", 0.0], ["Bei Lokalbahnzeile links abbiegen", 99, 43, 24, "99 m", "N", 0.7, "TL", 271.8]] }
      //alert(JSON.stringify(route));
      //alert(route.route_summary.total_distance);

      L.polyline(route.route_geometry).addTo(map);

      var pol = GetPolygon(route.route_geometry);
      L.polygon(pol).addTo(map);
    });

}

function GetPolygon(polyline) {

}

$(function () { // called after page Load (used like Main)
  map = InitializeMap();

  $('#drawAreaButton').click(function () { //eventhandler für button
    //alert(area);
    //L.polygon(area).addTo(map);

    DrawRoute(start, end);

  });

  $('#clearAreaButton').click(function () { //eventhandler für button
    area = [];
  });

  $('#DrawUmriss').click(function () { //eventhandler für button
    var POLY = [                  //Initialisierung eines beliebigen Polygonzugs
        //[48.00816, 16.235531], [48.007969, 16.235661], [48.007141, 16.23617], [48.007359, 16.23703], [48.007511, 16.237801], [48.00708, 16.237961], [48.006611, 16.238689], [48.005459, 16.239941], [48.005589, 16.24048], [48.005669, 16.24119], [48.005699, 16.24177], [48.005669, 16.242371], [48.005589, 16.242979], [48.00552, 16.24374], [48.005379, 16.243879], [48.005169, 16.244289], [48.005058, 16.244459], [48.00494, 16.244459], [48.004082, 16.245729], [48.00388, 16.24604], [48.00367, 16.24633], [48.003399, 16.24671], [48.003189, 16.247101], [48.002979, 16.247351], [48.002289, 16.247589], [48.00227, 16.24802], [48.002399, 16.249491], [48.002541, 16.25045], [48.002579, 16.2507], [48.002529, 16.250731], [48.002491, 16.250811], [48.002491, 16.25091], [48.002529, 16.250971], [48.002468, 16.25111], [48.002411, 16.25135], [48.002331, 16.25185], [48.00227, 16.252399], [48.002251, 16.25284], [48.002319, 16.25308], [48.002548, 16.253771], [48.00267, 16.254419], [48.00272, 16.2563], [48.00275, 16.25639], [48.002769, 16.257259], [48.002869, 16.257259], [48.00293, 16.257271], [48.003559, 16.25761]
        [16.220034, 48.022057], [16.218332, 48.022057], [16.216234, 48.022152], [16.215944, 48.022076], [16.215101, 48.02204], [16.21428, 48.02197], [16.213741, 48.02193], [16.213259, 48.02195], [16.212833, 48.02197], [16.212494, 48.021683], [16.21221, 48.021305], [16.21187, 48.02096], [16.211672, 48.02085], [16.211388, 48.020794], [16.210766, 48.020737], [16.209972, 48.02078], [16.209717, 48.020817], [16.209406, 48.02087], [16.207335, 48.02127], [16.207165, 48.021156], [16.206995, 48.021008], [16.206003, 48.021255], [16.205523, 48.02137], [16.205153, 48.021465], [16.204672, 48.02158], [16.204247, 48.02175], [16.203423, 48.022186], [16.203396, 48.02234], [16.203367, 48.022568], [16.203028, 48.022587], [16.202856, 48.022587], [16.202347, 48.022453], [16.201553, 48.022038], [16.201412, 48.02198], [16.201355, 48.02196], [16.201185, 48.02189], [16.201015, 48.02189], [16.200903, 48.021908], [16.200674, 48.02198], [16.200562, 48.022076], [16.200504, 48.022133], [16.200222, 48.02238], [16.199766, 48.02295], [16.19954, 48.02312], [16.199116, 48.02331], [16.19869, 48.023445], [16.198208, 48.023502], [16.197302, 48.02358], [16.196707, 48.02354], [16.196253, 48.02343], [16.19577, 48.023277], [16.195118, 48.02307], [16.194893, 48.023052], [16.194609, 48.02307], [16.19441, 48.023148], [16.194183, 48.02326], [16.193787, 48.02364], [16.19356, 48.023926], [16.193304, 48.024193], [16.193077, 48.024437], [16.192568, 48.02423], [16.191973, 48.02383], [16.19166, 48.023663], [16.191462, 48.023567], [16.191122, 48.0233], [16.190613, 48.023018], [16.19013, 48.02268], [16.189903, 48.02241], [16.18982, 48.022316], [16.189724, 48.022224], [16.18965, 48.02194], [16.189537, 48.021652], [16.189566, 48.02116], [16.189592, 48.021103], [16.189678, 48.020893], [16.189848, 48.02072], [16.190115, 48.020657], [16.19026, 48.020634], [16.190569, 48.020584], [16.19073, 48.020428], [16.190893, 48.020176]
    ];

    var ROUTE = [
        [48.00816, 16.235531], [48.007969, 16.235661], [48.007141, 16.23617], [48.007359, 16.23703], [48.007511, 16.237801], [48.00708, 16.237961], [48.006611, 16.238689], [48.005459, 16.239941], [48.005589, 16.24048], [48.005669, 16.24119], [48.005699, 16.24177], [48.005669, 16.242371], [48.005589, 16.242979], [48.00552, 16.24374], [48.005379, 16.243879], [48.005169, 16.244289], [48.005058, 16.244459], [48.00494, 16.244459], [48.004082, 16.245729], [48.00388, 16.24604], [48.00367, 16.24633], [48.003399, 16.24671], [48.003189, 16.247101], [48.002979, 16.247351], [48.002289, 16.247589], [48.00227, 16.24802], [48.002399, 16.249491], [48.002541, 16.25045], [48.002579, 16.2507], [48.002529, 16.250731], [48.002491, 16.250811], [48.002491, 16.25091], [48.002529, 16.250971], [48.002468, 16.25111], [48.002411, 16.25135], [48.002331, 16.25185], [48.00227, 16.252399], [48.002251, 16.25284], [48.002319, 16.25308], [48.002548, 16.253771], [48.00267, 16.254419], [48.00272, 16.2563], [48.00275, 16.25639], [48.002769, 16.257259], [48.002869, 16.257259], [48.00293, 16.257271], [48.003559, 16.25761]
    ];

    var KarthesischeROUTE = [];
    for (i = 0; i < ROUTE.length; i++) {
      KarthesischeROUTE.push([ROUTE[i][1], ROUTE[i][0]]);
    }

    function TEST_Umriss(POLY, RADIUS) {

      /* TEST */
      //var UMRISS = Umriss(POLY, RADIUS);
      var UMRISS = Umriss2(POLY, RADIUS)[0];

      /* DATEN UMWANDLUNG */
      var LatLng_UMRISS = [];         //Umwandeln in Lat,- and Length Koordinates
      for (var i = 0; i < UMRISS.length; i++) {
        LatLng_UMRISS.push(new L.LatLng(UMRISS[i][1], UMRISS[i][0]));
      }

      /* TEST-AUSGABE */
      var i = UMRISS.length;
      $('#outputx').html('[Lat,Lng] = [ <b>' + UMRISS[i - 1][1] + ' ; ' + UMRISS[i - 1][0] + ' ]</b>');
      $('#outputy').html('[Lat,Lng] = [ <b>' + UMRISS[0][1] + ' ; ' + UMRISS[0][0] + ' ]</b>');
      $('#PunkteZahl').html('|UmrissPunkte| = <b>' + UMRISS.length + '</b>');

      L.polygon(LatLng_UMRISS).addTo(map);
    }

    function TEST_Umriss2(POLY, RADIUS) {
      /* TEST */
      //var UMRISS = Umriss(POLY, RADIUS);

      var UMRISS = Umriss2(POLY, RADIUS);

      for (var k = 0; k < UMRISS.length; k++) {
        var UmrissPart = UMRISS[k];

        /* DATEN UMWANDLUNG */
        var LatLng_UMRISS = [];         //Umwandeln in Lat,- and Length Koordinates
        for (var i = 0; i < UmrissPart.length; i++) {
          LatLng_UMRISS.push(new L.LatLng(UmrissPart[i][1], UmrissPart[i][0]));
        }

        /* TEST-AUSGABE */
        var i = UmrissPart.length;
        $('#outputx').html('[Lat,Lng] = [ <b>' + UmrissPart[i - 1][1] + ' ; ' + UmrissPart[i - 1][0] + ' ]</b>');
        $('#outputy').html('[Lat,Lng] = [ <b>' + UmrissPart[0][1] + ' ; ' + UmrissPart[0][0] + ' ]</b>');
        $('#PunkteZahl').html('|UmrissPunkte| = <b>' + UmrissPart.length + '</b>');

        L.polygon(LatLng_UMRISS).addTo(map);
      }
    }

    //TEST_Umriss(POLY, 0.0001);
    //TEST_Umriss(POLY, 0.0002);
    //TEST_Umriss(POLY, 0.0003);
    //TEST_Umriss(POLY, 0.0004);
    //TEST_Umriss(POLY, 0.0005);
    TEST_Umriss2(POLY, 0.0005);
    TEST_Umriss2(KarthesischeROUTE, 0.002);

    //TEST_Umriss(KarthesischeROUTE, 0.0005);



  });

  $('#Testing_Umriss3').click(function () {

    /* Initialisierung von TestPolygonZygen */
    var POLY = [
                  [16.220034, 48.022057], [16.218332, 48.022057], [16.216234, 48.022152], [16.215944, 48.022076], [16.215101, 48.02204], [16.21428, 48.02197], [16.213741, 48.02193], [16.213259, 48.02195], [16.212833, 48.02197], [16.212494, 48.021683], [16.21221, 48.021305], [16.21187, 48.02096], [16.211672, 48.02085], [16.211388, 48.020794], [16.210766, 48.020737], [16.209972, 48.02078], [16.209717, 48.020817], [16.209406, 48.02087], [16.207335, 48.02127], [16.207165, 48.021156], [16.206995, 48.021008], [16.206003, 48.021255], [16.205523, 48.02137], [16.205153, 48.021465], [16.204672, 48.02158], [16.204247, 48.02175], [16.203423, 48.022186], [16.203396, 48.02234], [16.203367, 48.022568], [16.203028, 48.022587], [16.202856, 48.022587], [16.202347, 48.022453], [16.201553, 48.022038], [16.201412, 48.02198], [16.201355, 48.02196], [16.201185, 48.02189], [16.201015, 48.02189], [16.200903, 48.021908], [16.200674, 48.02198], [16.200562, 48.022076], [16.200504, 48.022133], [16.200222, 48.02238], [16.199766, 48.02295], [16.19954, 48.02312], [16.199116, 48.02331], [16.19869, 48.023445], [16.198208, 48.023502], [16.197302, 48.02358], [16.196707, 48.02354], [16.196253, 48.02343], [16.19577, 48.023277], [16.195118, 48.02307], [16.194893, 48.023052], [16.194609, 48.02307], [16.19441, 48.023148], [16.194183, 48.02326], [16.193787, 48.02364], [16.19356, 48.023926], [16.193304, 48.024193], [16.193077, 48.024437], [16.192568, 48.02423], [16.191973, 48.02383], [16.19166, 48.023663], [16.191462, 48.023567], [16.191122, 48.0233], [16.190613, 48.023018], [16.19013, 48.02268], [16.189903, 48.02241], [16.18982, 48.022316], [16.189724, 48.022224], [16.18965, 48.02194], [16.189537, 48.021652], [16.189566, 48.02116], [16.189592, 48.021103], [16.189678, 48.020893], [16.189848, 48.02072], [16.190115, 48.020657], [16.19026, 48.020634], [16.190569, 48.020584], [16.19073, 48.020428], [16.190893, 48.020176]
    ];

    var PHI = Math.PI;
    var SINPHI = Math.sin(PHI);
    var COSPHI = Math.cos(PHI);

    /* Normierung eines Vectors */
    function NormVec(VEC, LENG) {
      var VecNorm = [0, 0];
      var Norm = (LENG / Math.sqrt(VEC[0] * VEC[0] + VEC[1] * VEC[1]));
      VecNorm[0] = VEC[0] * Norm;
      VecNorm[1] = VEC[1] * Norm;
      return VecNorm;
    }

    /* Rechteckige Bereichsbestimung um die Gerade-Verbindung der Punkte P1 zu P2 */
    function CalculateRectangleArea(P1, P2, RADIUS) {
      var Area = [];
      var RVec = [0, 0];

      /* Berechnung des Normalenvektors auf die Verbindungsgerade von P1 zu P2 */
      RVec[0] = -(P2[1] - P1[1]);
      RVec[1] = P2[0] - P1[0];
      RVec = NormVec(RVec, RADIUS);

      /* Berechnung des von den Punkten bestimmten Bereich */
      Area.push([(P1[0] + RVec[0]), (P1[1] + RVec[1])]);
      Area.push([(P1[0] - RVec[0]), (P1[1] - RVec[1])]);
      Area.push([(P2[0] - RVec[0]), (P2[1] - RVec[1])]);
      Area.push([(P2[0] + RVec[0]), (P2[1] + RVec[1])]);

      return Area;
    }

    /* Gibt Boolsche aussage über die Enthaltenkeit des POINT in einer Rechteckigen Umgebung um die Punkte P1 und P2 zurück */
    function isPOINTinArea(POINT, AREA) {

      function KreuzProdTest(A, B, C) {
        if (A[1] == B[1] == C[1]) {
          if ((B[0] <= A[0] <= C[0]) || (C[0] <= A[0] <= B[0])) {
            return 0;
          }
          else {
            return 1;
          }
        }
        if (B[1] > C[1]) {
          var temp = B;
          B = C;
          C = temp;
        }
        if ((A[1] == B[1]) & (A[0] == B[0])) {
          return 0;
        }
        if ((A[1] <= B[1]) || (A[1] > C[1])) {
          return 1;
        }
        var Delta = ((B[0] - A[0]) * (C[1] - A[1])) - ((B[1] - A[1]) * (C[0] - A[0]));
        if (Delta > 0) {
          return -1;
        }
        else {
          if (Delta < 0) {
            return 1;
          }
          else {
            return 0;
          }
        }
      }

      AREA.push(AREA[0]);
      var T = -1;
      for (var i = 0; i < (AREA.length - 1) ; i++) {
        T = T * KreuzProdTest(POINT, AREA[i], AREA[i + 1]);
      }
      return T;
    }

    function SimplifyPolyline(POLY, GENAU) {
      var SimplPoly = POLY[0];
      var i = 0;
      while (i < (POLY.length - 1)) {
        var allElement = 1;
        var k = 1;
        while (allElement & ((i + k) < POLY.length)) {
          var LineProx = CalculateRectangleArea(POLY[i], POLY[i + k + 1], GENAU);
          for (m = i + 1; m < i + k; m++) {
            if (isPOINTinArea(POLY[m], LineProx) != 1) {
              SimplPoly.push(POLY[i + k]);
              break;
            }
            else {
              k = k + 1;
            }
          }
        }
      }
      return SimplPoly;
    }

    /* Testdaten in Karte Zeichnen */
    var Area = CalculateRectangleArea([16.220034, 48.022057], [16.21428, 48.02197], 0.0005);

    /* DATEN UMWANDLUNG */
    var LatLng_Area = [];         //Umwandeln in Lat,- and Length Koordinates
    for (var i = 0; i < Area.length; i++) {
      LatLng_Area.push(new L.LatLng(Area[i][1], Area[i][0]));
    }
    L.polygon(LatLng_Area).addTo(map);

    var SimpPol = SimplifyPolyline(POLY, 0.005);

    /* DATEN UMWANDLUNG */
    var LatLng_SimplPoly = [];         //Umwandeln in Lat,- and Length Koordinates
    for (var i = 0; i < SimpPol.length; i++) {
      LatLng_SimplPoly.push(new L.LatLng(SimpPol[i][1], SimpPol[i][0]));
    }
    L.polygon(LatLng_SimplPoly).addTo(map);

    /* Test von isPOINTinArea */
    A = [16.220000, 48.022057]; //in Area
    B = [16.220034, 48.022057]; //auf Kante
    C = [16.420034, 47.902057]; //nicht in Area
    var AinPoly = isPOINTinArea(A, Area);
    var BinPoly = isPOINTinArea(B, Area);
    var CinPoly = isPOINTinArea(C, Area);

    $('#Phi').html('<b>' + PHI + '</b>');
    $('#SinPhi').html('<b>' + SINPHI + '</b>');
    $('#CosPhi').html('<b>' + COSPHI + '</b>');
    $('#MaechtigkeitPoly').html('<b>' + LatLng_Area.length + '</b>');
    $('#AinPoly').html('<b>' + AinPoly + '</b>');
    $('#BinPoly').html('<b>' + BinPoly + '</b>');
    $('#CinPoly').html('<b>' + CinPoly + '</b>');

  });
});

